package com.hfzy.ihk.web.linkcall.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class TaskExecutePool {
    @Bean
    public Executor taskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        TaskThreadPoolConfig config = new TaskThreadPoolConfig(10,15,50,60);
        //初始线程大小
        executor.setCorePoolSize(config.getCorePoolSize());
        //最大线程大小
        executor.setMaxPoolSize(config.getMaxPoolSize());
        //设置队列长度
        executor.setQueueCapacity(config.getQueueCapacity());
        //设置多长时间，线程回收
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        /**
         *
         1. CallerRunsPolicy ：这个策略重试添加当前的任务，他会自动重复调用 execute() 方法，直到成功。
         2. AbortPolicy ：对拒绝任务抛弃处理，并且抛出异常。
         3. DiscardPolicy ：对拒绝任务直接无声抛弃，没有异常信息。
         4. DiscardOldestPolicy ：对拒绝任务不抛弃，而是抛弃队列里面等待最久的一个线程，然后把拒绝任务加到队列。
         * */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    private class TaskThreadPoolConfig{
        private int corePoolSize;
        private int maxPoolSize;
        private int keepAliveSeconds;
        private int queueCapacity;
        public TaskThreadPoolConfig(int corePoolSize,int maxPoolSize,int keepAliveSeconds,int queueCapacity){
            this.corePoolSize = corePoolSize;
            this.maxPoolSize = maxPoolSize;
            this.keepAliveSeconds = keepAliveSeconds;
            this.queueCapacity = queueCapacity;
        }
        public int getCorePoolSize() {
            return corePoolSize;
        }
        public int getMaxPoolSize() {
            return maxPoolSize;
        }
        public int getKeepAliveSeconds() {
            return keepAliveSeconds;
        }
        public int getQueueCapacity() {
            return queueCapacity;
        }
    }
}
